package com.zstu.mall.utils;

import com.zstu.mall.entity.UploadImage;
import com.zstu.mall.service.UploadImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.util.List;

@Component
public class FileUtil {

    @Autowired
    private UploadImageService uploadImageService;

    private static FileUtil fileUtil;

    //服务器加载Servlet(只)执行一次
    @PostConstruct
    public void init(){
        fileUtil = this;
        fileUtil.uploadImageService = this.uploadImageService;
    }

    /**
     * 保存上传的文件
     *
     * @param file
     * @return 文件名
     * @throws Exception
     */
    public static String saveFile(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty())
            return "";
        File target = new File("src\\main\\resources\\static\\image");
        if (!target.isDirectory()) {
            target.mkdirs();
        }
        UploadImage uploadImage = new UploadImage();
        String originalFilename = file.getOriginalFilename();
        //信息摘要算法
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(file.getBytes());
        String fileName = (Helper.bytesToHex(md.digest(),0,md.digest().length-1)) + "." + getPostfix(originalFilename);
        File file1 = new File(target.getPath() + "/" + fileName);
        //判断是否存在
        boolean existImage = false;
        for(UploadImage uploadImage2 : fileUtil.uploadImageService.findAll()){
            if(uploadImage2.getNewName().equals(fileName))
                existImage = true;
        }
        uploadImage.setId(fileUtil.uploadImageService.createId());
        uploadImage.setNewName(fileName);
        uploadImage.setOldName(originalFilename);
        //创建文件
        if(!existImage){
            Files.write(Paths.get(file1.toURI()), file.getBytes(), StandardOpenOption.CREATE_NEW);
            fileUtil.uploadImageService.create(uploadImage);
            return uploadImage.getId();
        }
        return fileName;
    }

    /**
     * 获得文件的后缀名
     *
     * @param fileName
     * @return
     */
    public static String getPostfix(String fileName) {
        if (fileName == null || "".equals(fileName.trim())) {
            return "";
        }
        if (fileName.contains(".")) {
            return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        }
        return "";
    }

}
